<?php
//$Id: indent.php 9 2009-04-26 06:35:12Z bole.Chen $
uses('model');

class indentModel extends Model {

    function __construct() {
        parent::__construct();
    }

    //订单付款验证
    function pay($v) {
        $this->dbconnect();

        if ($data['list'] = $this->db->GetRow($this->table['indent'], '*', "id={$v['id']} AND stat = 0")) {
            $data['code']['pay'] = 1;
        } else {
            $data['code']['pay'] = 2;
        }

        return $data;
    }

    //在线支付
    function payNow($v) {
        $this->dbconnect();

        $d = $this->pay($v);
        if ($d['code']['pay'] != 1) {
            $data['code']['payNow'] = 4;
        } else {
            $data = $d;

            //生成新的订单号，以防止支付失败再支付时拒绝。规则：原订单号+000+随机数字3位
            //$data['list']['id'] = $data['list']['id'].'000'.rand(100,999);

            uses('pay');
            $pm = Pay::getName($v['type']);
            $pay = Pay::getModel($pm);

            $data['url'] = $pay->payTo($data['list']);
        }

        return $data;
    }

    //支付结果返回
    function payResult($v) {
        uses('pay');
        $pm = Pay::getName($v['type']);
        $pay = Pay::getModel($pm);

        /*
        1.支付成功
        2.非法定单
        4.确认到货 - alipay
        8.支付失败
        16.实际金额不对
        */
        $r = $pay->payResult();

        if ($pay->id) {

            //订单号还原
            //if (substr($pay->id, -6, 3) == '000') $pay->id = substr($pay->id, 0, -6);

            //取得返回的订单ID
            $this->dbconnect();
            $d = $this->pay(array('id'=>$pay->id));

            if ($r['code']['payResult'] == 4) {
                //收到物品处理 only for alipay now
                $fields['stat'] = 4;
                $fields['log'] .= $d['list']['log'].date('Y-m-d H:i:s')." [系统] 支付宝通知到货，订单完成\n";

                if ($this->db->Update($this->table['indent'], $fields, "id=".$pay->id))
                    die('Y');
                else
                    die('N');

            } else {
                //验证ID合法性 及收款处理
                if ($d['code']['pay'] != 1) {
                    $data['code']['payResult'] = 2;
                } else {

                    $d = $d['list'];
                    $data['data'] = $d;

                    if ($r['code']['payResult'] == 1) {

                        //检查实付金额
                        $fee = number_format($d['sumfee']+$d['postfee']+$d['adjustfee'], 2);
                        if ($r['pay'] >= $fee) {

                            //支付成功后改变定单状态为待发货
                            //$fields['stat'] = 2;
                            //$fields['log'] .= $d['log'].date('Y-m-d H:i:s')." [系统] 订单通过在线支付({$pm})成功\n";
                            //$this->db->Update($this->table['indent'], $fields, "id={$d['id']}");

                            //付款成功后续处理
                            //权限提升
                            $v['admin'] = true;

                            $v['id']    = $pay->id;
                            $v['stat']  = 2;
                            $v['log']   .= $d['log'].date('Y-m-d H:i:s')." [系统] 订单通过在线支付({$pm})成功\n";
                            $this->indentsUpdate($v);

                        } else {
                            $r['code']['payResult'] = 16;
                        }
                    } else {
                        //die('Stop u hack!!');
                        $r['code']['payResult'] = 2;
                    }

                    $data['code']['payResult'] = $r['code']['payResult'];
                }
            }

        } else {
            $data['code']['payResult'] = 2;
        }

        return $data;
    }

    function indentsList($v) {
        $this->dbconnect();

        if ($v['sort']) {
            $cols = $this->db->_db->MetaColumnNames($this->table['indent']);
            if (!in_array($v['sort'],$cols)) $v['sort'] = 'id';
        } else {
            $v['sort'] = 'id';
        }

        if ($v['uid']) {
            $where = "uid={$v['uid']}";
            if ($v['id']) {
                //检查是否我的定单
                if ($this->db->GetOne($this->table['indent'], 'uid', "id = {$v['id']}") == $v['uid']) {
                    //详情表
                    $data['detail']['list'] = $this->db->GetAll($this->table['indentd'], '*', "idid = {$v['id']}");
                    if ($data['detail']['list']) {
                        $tmp = $this->db->GetRow($this->table['indentd'], 'SUM(amount) as a, SUM(amount*price) as b', "idid ={$v['id']}");
                        $data['detail']['totalamount']  = $tmp['a'];
                        $data['detail']['totalprice']   = $tmp['b'];
                    } else {
                        //存档订单读取详情字段
                        $data['detail']['list'] = unserialize($this->db->GetOne($this->table['indent'], 'data', "id = {$v['id']}"));
                        if (is_array($data['detail']['list'])) foreach ($data['detail']['list'] as $item) {
                            $data['detail']['totalamount']  += $item['amount'];
                            $data['detail']['totalprice']   += $item['amount']*$item['price'];
                        }
                    }

                    //err订单
                    if (!$data['detail']['list']) $this->db->Delete($this->table['indent'], "id = {$v['id']}");
                }

                $where .= " AND id = {$v['id']}";
            }

            if ($v['where']) $where .= " AND {$v['where']}";
        } else {
            if ($v['id']) {
                //详情表
                $data['detail']['list'] = $this->db->GetAll($this->table['indentd'], '*', "idid = {$v['id']}");
                if ($data['detail']['list']) {
                    $tmp = $this->db->GetRow($this->table['indentd'], 'SUM(amount) as a, SUM(amount*price) as b', "idid ={$v['id']}");
                    $data['detail']['totalamount']  = $tmp['a'];
                    $data['detail']['totalprice']   = $tmp['b'];
                } else {
                    //存档订单读取详情字段
                    $data['detail']['list'] = unserialize($this->db->GetOne($this->table['indent'], 'data', "id = {$v['id']}"));
                    if (is_array($data['detail']['list'])) foreach ($data['detail']['list'] as $item) {
                        $data['detail']['totalamount']  += $item['amount'];
                        $data['detail']['totalprice']   += $item['amount']*$item['price'];
                    }
                }

                $where .= "id = {$v['id']}";
            } else {
                $where = $v['search'] ? $this->makelikequery($v['search'], array('id','linkman','address','tel','zipcode'), $this->db) : $v['where'];
            }
        }

        if ($v['pagesize']) {
            //$rs = $this->db->Limit($this->table['users'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}", intval($v['pagestart']), $v['pagesize']);
            $data['list'] = $this->db->GetPage(array($this->table['indent'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}"), $data['page'], $v['pagesize']);
        } else
            $data['list'] = $this->db->GetAll($this->table['indent'], '*', "$where ORDER BY ".$v['sort']." {$v['sortorder']}");

        return $data;
    }

    function indentsUpdate($v) {
        $this->dbconnect();

        $admin  = $v['admin'];
        $uid    = $v['uid'];

        if ($admin && $v['remove']) {

            //订单删除 (只允许删除存档订单)
            if ($this->db->Count($this->table['indent'], "id={$v['id']} AND stat=-1")) {
                $this->db->Delete($this->table['indent'], "id={$v['id']} AND stat=-1");
                //$this->db->Delete($this->table['indentd'], "idid={$v['id']}");
                $data['remove'] = 1;
            }

        } else {

            $fields = $v;
            $fields['updated'] = time();
            //type 为支付类型
            unset($fields['id'], $fields['remove'], $fields['add'], $fields['admin'], $fields['uid'], $fields['type']);

            $row = $this->db->GetRow($this->table['indent'], '*', "id={$v['id']}");

            if ($admin || ($row['uid'] == $uid)) {
                //非存档订单->存档操作
                if ($row['stat'] != -1 && $v['stat'] == -1) {
                    $f['stat'] = $v['stat'];
                    $data['code']['indentsUpdate'] = $this->db->Update($this->table['indent'], $f, "id={$v['id']}") ? 1 : 2;
                    unset($f);

                    //1.存档相关数据
                    $items = $this->db->GetAll($this->table['indentd'], 'iid,iname,amount,price', "idid={$v['id']}");

                    //2.防止手动在数据库中更新定单状态时，数据不一致现象出现
                    if (count($items) > 0) $fields['data'] = serialize($items);

                    $fields['log']  = $row['log'] . ($fields['log'] ? $fields['log']."\n" : date('Y-m-d H:i:s')." [". ($admin ? '系统' : '用户') ."] 订单取消\n");
                    $this->db->Update($this->table['indent'], $fields, "id={$v['id']}");

                    //3.返还库存
                    if (count($items) > 0) foreach ($items as $item) $this->db->Update($this->table['items'], array('stocknum'=>"{[+{$item['amount']}]}"), "id={$item['iid']}");
                    $this->db->Delete($this->table['indentd'], "idid={$v['id']}");

                    //4.折扣代码返还
                    if ($v['adjustfee']) {
                        //$this->db->Update($this->table['voucher'], array('iid'=>NULL), "iid={$v['id']}");
                        $vc =& getController('voucher');
                        $vc->VoucherIndent(array('remove'=>1, 'iid'=>$v['id'], 'vid'=>'1'));
                    }

                    //5.定单返点返还
                    if ($row['camefrom'] && $row['backpoint']) {
                        $sC =& getController('score');
                        $sC->delByiid($v['id']);
                    }

                    //如果是管理员取消的定单则发mail提醒用户
                    if ($admin) {
                        if ($row['uid']) $row1 = $this->db->GetRow($this->table['users'], 'username, nickname, email', "id={$row['uid']}");
                        $email = $row['cemail'] ? $row['cemail'] : $row1['email'];
                        $nickname = $row1['nickname'] ? $row1['nickname'] : $row['cman'];

                        if ($email) {
                            $f['subject']   =   "乐铺 {$v['id']} 号订单取消通知 - ".date('Y-m-d H:i');
                            $f['mailto']    =   $email;
                            $f['body']      =   "亲爱的{$nickname}：\r\n\r\n";
                            $f['body']      .=  "感谢您对乐铺的支持并承蒙订购。因至今尚未收到您的订单付款。故已先为您取消该订单。\r\n\r\n";
                            $f['body']      .=  "若您日后仍有所需，请到我们的网站 LooPo.cn 重新订购，期待为您再次服务。";
                            $f['created']   =   time();
                            $this->db->Insert($this->table['mail'], $f);
                        }
                    }

                    //短信通知客户
                    uses('sms');
                    $sms =& new Sms;
                    $sms->cancelIndent($row['cphone']?$row['cphone']:$row['tel'],$v['id']);

                } else {
                    //确认收款、在线支付成功处理
                    //1.存档相关数据
                    if ($row['stat'] < 2 && $v['stat'] == 2) {
                        $items = $this->db->GetAll($this->table['indentd'], 'iid,iname,amount,price', "idid={$v['id']}");
                        if ($items) $fields['data'] = serialize($items);

                        //2.定单返点
                        if ($row['camefrom']) {
                            $sC =& getController('score');
                            $sC->updateScore($row['camefrom'], $row['id'], 2, $row['backpoint']);
                        }

                        //3.短信通知客户
                        uses('sms');
                        $sms =& new Sms;
                        $sms->payIndent($row['cphone']?$row['cphone']:$row['tel'], $v['id'], $row['sumfee']+$row['adjustfee']);

                        //4.Email 通知注册用户
                        if ($row['uid']) $row1 = $this->db->GetRow($this->table['users'], 'username, nickname, email', "id={$row['uid']}");
                        $email = $row['cemail'] ? $row['cemail'] : $row1['email'];
                        $nickname = $row1['nickname'] ? $row1['nickname'] : $row['cman'];

                        if ($email) {
                            $f['subject']   =   "乐铺 {$v['id']} 号订单已经收到您的付款 - ".date('Y-m-d H:i');
                            $f['mailto']    =   $email;
                            $f['body']      =   "亲爱的{$nickname}：\r\n\r\n";
                            $f['body']      .=  "感谢您对乐铺的支持并承蒙订购。我们已经收到了您的 {$v['id']} 号订单的付款。\r\n\r\n";
                            $f['body']      .=  "我们会在 2 天内为您发出物品，届时会再次通过 email 通知您。您也可以随时登录乐铺用户中心，在 “我的订单管理” 中来查看您的订单状态。\r\n\r\n";
                            $f['body']      .=  "祝您购物愉快。";
                            $f['created']   =   time();
                            $this->db->Insert($this->table['mail'], $f);
                        }

                        if ($row['meta']) {
                            $meta = serialize($row['meta']);
                            $gift = $meta['gift'];
                        }

                        //5.礼品卡自动发货处理
                        if ($gift && !$row['zipcode']) {
                            //5.1 插入折扣券表
                            $vv['price']     = $row['sumfee'];
                            $vv['minprice']  = 1;
                            $vv['prend']     = 'GIFT';
                            $vv['expiredtime']= time()+3600*24*365*10; //有效期十年
                            $vc =& getController('voucher');
                            $result = $vc->addVoucher($vv);

                            //5.2 发 Mail
                            if ($result != 2) {
                                $mc =& getController('mail');
                                $maildata = $row;
                                $maildata['vc'] = $result;
                                $mc->sendGiftCard($maildata);
                            }

                            //5.3 自动发货
                            $fields['postnum'] = $v['postnum'] = $maildata['vc'];
                            $row['log'] = $row['log'] . ($fields['log'] ? $fields['log']."\n" : date('Y-m-d H:i:s')." [". ($admin ? '系统' : '用户') ."] 礼品卡生成 - 代码: <b>{$maildata['vc']}</b>\n");
                            $fields['stat'] = $v['stat'] = 3;
                        }
                    }

                    //发货
                    if ($row['stat'] <> 3 && $v['stat'] == 3) {
                        $fields['log'] = $row['log'] . ($fields['log'] ? $fields['log']."\n" : date('Y-m-d H:i:s')." [". ($admin ? '系统' : '用户') ."] 订单发货\n");

                        if ($v['posttype'] && $v['postnum']) {
                            //1.短信通知客户发货
                            uses('sms');
                            $sms = new Sms;
                            $sms->postIndent($row['cphone']?$row['cphone']:$row['tel'],$v['id'],$v['postnum'],$v['posttype']);

                            //4.Email 通知注册用户
                            if (!$gift) {
                                if ($row['uid']) $row1 = $this->db->GetRow($this->table['users'], 'username, nickname, email', "id={$row['uid']}");
                                $email = $row['cemail'] ? $row['cemail'] : $row1['email'];
                                $nickname = $row1['nickname'] ? $row1['nickname'] : $row['cman'];

                                if ($email) {
                                    $f['subject']   =   "乐铺 {$v['id']} 号订单已经出货 - ".date('Y-m-d H:i');
                                    $f['mailto']    =   $email;
                                    $f['body']      =   "亲爱的{$nickname}：\r\n\r\n";
                                    $f['body']      .=  "感谢您对乐铺的支持并承蒙订购。您的 {$v['id']} 号订单已经为您发出。\r\n\r\n";

                                    if ($row['postfee'] > 20) {
                                        $f['body'] .= "您选择的物流方式是 {$row['posttype']}，正常情况下 1 周内即可送达，最迟会在 2 周内到达。\r\n\r\n";
                                        $lasttime = time()+3600*24*7*2;
                                    } elseif ($row['postfee'] > 10) {
                                        $f['body'] .= "您选择的物流方式是 {$row['posttype']}，正常情况下 2-3 天即可送达，最迟会在 1 周内到达。\r\n\r\n";
                                        $lasttime = time()+3600*24*6;
                                    } else {
                                        $f['body'] .= "您选择的物流方式是 {$row['posttype']}，正常情况下 1-2 周即可送达，最迟会在 1 月内到达。\r\n\r\n";
                                        $lasttime = time()+3600*24*30;
                                    }

                                    $f['body']      .=  "如果您在 ". date('Y-m-d', $lasttime) ." 还没未收到物品，请与我们取得联系。您也可以随时登录乐铺用户中心，在 “我的订单管理” 中来查看订单的物流状态。\r\n\r\n";
                                    $f['body']      .=  "祝您购物愉快，期待为您再次服务。";
                                    $f['created']   =   time();

                                    $this->db->Insert($this->table['mail'], $f);
                                }
                            }
                        }
                    }

                    //确认收货
                    if ($v['stat'] == 4) $fields['log'] = $row['log'] . ($fields['log'] ? $fields['log']."\n" : date('Y-m-d H:i:s')." [". ($admin ? '系统' : '用户') ."] 确认收货，定单完成\n");

                    $data['code']['indentsUpdate'] = $this->db->Update($this->table['indent'], $fields, "id={$v['id']}") ? 1 : 2;
                }
            } else {
                $data['code']['indentsUpdate'] = 2;
            }
        }

        return $data;
    }

    //清理定单
    function indentsClear($v=null) {
        $this->dbconnect();

        //清除 $cfg['indent_expire'] 天外订单
        //TODO 考虑Cahce
        $rows = $this->db->GetAll($this->table['indent'].' a LEFT JOIN '.$this->table['users'].' b ON a.uid = b.id', 'a.id, a.cman, a.cphone, a.cemail, b.nickname, b.email', time()."-a.created>3600*24*{$this->cfg['indent_expire']} AND stat = 0 ");
        if ($rows) {
            //提高权限
            $data['admin']  = true;

            $data['stat']   = -1;
            foreach ($rows as $row) {
                $data['id']     = $row['id'];
                $data['log']    = date('Y-m-d H:i:s').' [系统] 过期订单自动存档';
                $this->indentsUpdate($data);

                $email = $row['cemail'] ? $row['cemail'] : $row['email'];
                $nickname = $row['nickname'] ? $row['nickname'] : $row['cman'];

                if ($email) {
                    //过期订单Mail通知
                    $f['subject']   =   "乐铺 {$row['id']} 号订单过期通知 - ".date('Y-m-d H:i');
                    $f['mailto']    =   $email;
                    $f['body']      =   "亲爱的{$nickname}：\r\n\r\n";
                    $f['body']      .=  "感谢您对乐铺的支持并承蒙订购。因至今尚未收到您的订单付款。故已先为您取消该订单。\r\n\r\n";
                    $f['body']      .=  "若您日后仍有所需，请到我们的网站 LooPo.cn 重新订购，期待为您再次服务。";
                    $f['created']   =   time();
                    $this->db->Insert($this->table['mail'], $f);
                }
            }
            //$this->db->Update($this->table['indent'], array('stat'=>-1), 'id IN('. join(',', $clearid) .')');
            //$this->db->Delete($this->table['indentd'], 'idid IN('. join(',', $clearid) .')');
        }

        return true;
    }
}
